﻿using System;
using System.Web;
using System.Web.Security;

namespace MyLib.Web {
	/// <summary>
	/// 
	/// </summary>
	public sealed class CookiePathModule : IHttpModule {
		private string m_applicationPath;

		/// <summary>
		/// 
		/// </summary>
		public CookiePathModule() {
		}

		/// <summary>
		/// 
		/// </summary>
		public void Dispose() {
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		public void Init(HttpApplication context) {
			m_applicationPath = HttpRuntime.AppDomainAppVirtualPath;
			if (null != m_applicationPath && 0 == m_applicationPath.Length) m_applicationPath = null;
			context.PreSendRequestHeaders += OnPreSendRequestHeaders;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void OnPreSendRequestHeaders(object sender, EventArgs e) {
			HttpApplication application = (HttpApplication)sender;
			HttpContext context = application.Context;
			HttpCookieCollection cookies = context.Response.Cookies;
			if (null != cookies && 0 != cookies.Count) {
				for (int index = 0; index < cookies.Count; index++) {
					ProcessCookie(cookies[index]);
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="cookie"></param>
		private void ProcessCookie(HttpCookie cookie) {
			if (null != cookie) {
				string path = cookie.Path;
				if (!string.IsNullOrEmpty(path)) {
					if (path.StartsWith("~/", StringComparison.Ordinal)) {
						cookie.Path = m_applicationPath + path.Substring(1);
					} else if ("/" == path && null != m_applicationPath) {
						if (FormsAuthentication.FormsCookieName == cookie.Name) {
							cookie.Path = m_applicationPath + "/";
						}
					}
				}
			}
		}
	} // end of CookiePathModule.
}
